/*
 * Copyright (C) 2019 Baidu, Inc. All Rights Reserved.
 */
package com.bootdo.hjh.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bootdo.common.annotation.Log;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.R;
import com.bootdo.hjh.domain.ProductType;
import com.bootdo.hjh.domain.StockDO;
import com.bootdo.hjh.domain.TihuoOrderDO;
import com.bootdo.hjh.domain.UserAddress;
import com.bootdo.hjh.service.StockService;
import com.bootdo.hjh.service.TihuoOrderService;
import com.bootdo.hjh.service.UserAddressService;
import com.bootdo.system.domain.UserDO;

/**
 * 库存变更记录
 *
 * @author chglee
 * @email 1992lcg@163.com
 * @date 2019-04-08 15:26:46
 */

@Controller
public class StockController {
	@Autowired
	private StockService stockService;

	@Autowired
	private UserAddressService userAddressService;

	@Autowired
	private TihuoOrderService tihuoOrderService;


	@GetMapping("/stock")
	public String list(Model model){
		Subject subject = SecurityUtils.getSubject();
		Object obj = subject.getPrincipal();
		Long userId = ((UserDO)obj).getUserId();
		Integer dxlStock = stockService.myStockBalance(userId, ProductType.DU_XIAO_LI.getValue());
		Integer hmStock = stockService.myStockBalance(userId, ProductType.HEI_MEI.getValue());
		model.addAttribute("dxlStock", dxlStock);
		model.addAttribute("hmStock", hmStock);
		return "hjh/stock";
	}


	@Log("库存变更详情列表")
	@GetMapping("/stock/toList")
	public String toStockDetailList(Model model, @RequestParam(value = "type", required = false) Byte type) {
		model.addAttribute("type", type);
		return "hjh/stockDetail";
	}

	@Log("库存变更详情列表")
	@GetMapping("/stock/list")
	@ResponseBody
	public PageUtils stockList(@RequestParam(value = "type",defaultValue = "0") Integer type
			, @RequestParam(value = "beginDate",required = false) String beginDate
			, @RequestParam(value = "endDate",required = false) String endDate
			, @RequestParam("offset") Integer offset
			, @RequestParam("limit") Integer limit){
		//获取当前用户
		Subject subject = SecurityUtils.getSubject();
		Object obj = subject.getPrincipal();
		Long userId = ((UserDO)obj).getUserId();

		Date begin = null;
		Date end = null;
		try{
			if(StringUtils.isNotBlank(beginDate)){
				begin = new SimpleDateFormat("yyyy-MM-dd").parse(beginDate);
			}
			if(StringUtils.isNotBlank(endDate)){
				end = (new SimpleDateFormat("yyyy-MM-dd")).parse(endDate);
			}
		}catch(Exception ex){
		}

		List<StockDO> list = stockService.listStocks(userId,type,begin,end,offset,limit);
		int total = stockService.countStocks(userId,type,begin,end);

		PageUtils pageUtils = new PageUtils(list, total);

		return pageUtils;

	}

	/**
	 * 提货
	 */
	@GetMapping("/stock/tihuo")
	public String tihuo(Model model,
								@RequestParam(value = "type", defaultValue = "1", required = false) Integer type) {
		Subject subject = SecurityUtils.getSubject();
		Object obj = subject.getPrincipal();
		Long userId = ((UserDO)obj).getUserId();

		List<UserAddress> userAddressList = userAddressService.getUserAddressAll(userId);
		model.addAttribute("userAddressList", userAddressList);

		Integer stock = stockService.myStockBalance(userId, type);
		model.addAttribute("stock", stock);

		ProductType productType = ProductType.getByValue(type);
		model.addAttribute("type", type);
		model.addAttribute("typeName", productType.getName());
		return "hjh/tihuo";
	}

	/**
	 * 提货
	 */
	@PostMapping("/stock/tihuo")
	@ResponseBody
	@Transactional
	public R saveTihuo(@RequestBody Map<String, Integer> tihuo) {
		Subject subject = SecurityUtils.getSubject();
		Object obj = subject.getPrincipal();
		Long userId = ((UserDO)obj).getUserId();

		Integer amount = tihuo.get("amount");
		Integer type = tihuo.get("type");
		Integer addressId = tihuo.get("addressId");

		if (amount <= 0) {
			return R.error(1, "提货数量必须大于0");
		}
		ProductType productType = ProductType.getByValue(type);

		// 当前用户的库存
		Integer stock = stockService.myStockBalance(userId, type);
		if (stock < amount) {
			return R.error(1, "你的库存不足");
		}

		UserAddress address = userAddressService.getUserAddressById(addressId);
		if (address == null) {
			return R.error(2, "收货地址不存在");
		}

		String tihuoNo = com.bootdo.common.utils.StringUtils.generateOrderNO("");
		// 生成提货单
		TihuoOrderDO tihuoOrderDO = new TihuoOrderDO();
		tihuoOrderDO.setAddress(address.getAddress());
		tihuoOrderDO.setCity(address.getCity());
		tihuoOrderDO.setCountry(address.getCountry() +"");
		tihuoOrderDO.setCreateTime(new Date());
		tihuoOrderDO.setDistrict(address.getDistrict());
		tihuoOrderDO.setLastModifyTime(new Date());
		tihuoOrderDO.setMobile(address.getMobile());
		tihuoOrderDO.setPostcode(address.getPostcode());
		tihuoOrderDO.setProductId(productType.getProductId());
		tihuoOrderDO.setProductName(productType.getName());
		tihuoOrderDO.setProvince(address.getProvince());
		tihuoOrderDO.setQuality(amount);
		tihuoOrderDO.setReceiver(address.getName());
//		0 未发货 1.已发货 2.已收货
		tihuoOrderDO.setStatus(0);
		tihuoOrderDO.setTihuoNo(tihuoNo);
		tihuoOrderDO.setUserId(userId);
		tihuoOrderDO.setTel(address.getTel());

		tihuoOrderService.save(tihuoOrderDO);

		// 减库存
		int stockBalance = stock - amount;
		StockDO stockDO = new StockDO();
		stockDO.setAmount(-amount);
		stockDO.setBalance(stockBalance);
		stockDO.setCreateTime(new Date());
		stockDO.setLastModifyTime(new Date());
		stockDO.setProductType(productType.getValue());
		stockDO.setUserId(userId);
		stockDO.setRemark("会员提货扣减库存数量：" + amount);
		stockService.save(stockDO);

		return new R(tihuoOrderDO.getId());
	}

	@GetMapping("/stock/toMyTihuoOrder")
	public String toMyTihuoOrder(Model model, @RequestParam(value = "type", required = false) Integer type) {
		model.addAttribute("type", type);
		return "hjh/myTihuoOrder";
	}

	// 我的提货单
	@Log("我的提货单详情列表")
	@GetMapping("/stock/myTihuoOrder")
	@ResponseBody
	public PageUtils myTihuoOrder(@RequestParam(value = "type",defaultValue = "0") Integer type
			, @RequestParam("offset") Integer offset
			, @RequestParam("limit") Integer limit){
		//获取当前用户
		Subject subject = SecurityUtils.getSubject();
		Object obj = subject.getPrincipal();
		Long userId = ((UserDO)obj).getUserId();

		ProductType productType = ProductType.getByValue(type);

		List<TihuoOrderDO> list = tihuoOrderService.listTihuoOrders(userId,productType.getProductId(),offset,limit);
		int total = tihuoOrderService.countTihuoOrder(userId,productType.getProductId());

		PageUtils pageUtils = new PageUtils(list, total);

		return pageUtils;

	}

}
